
package com.kugou.game.sdk.utils;

import com.kugou.download.DownloadFile;
import com.kugou.download.FileDownloader;
import com.kugou.framework.base.LogUtil;
import com.kugou.game.sdk.api.common.BaseSDKConfig;
import com.kugou.game.sdk.api.common.IEventCode;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.api.online.KGPlatform;
import com.kugou.game.sdk.core.FolderManager;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.PlatformEventDispatcher;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.core.VipManager;
import com.kugou.game.sdk.download.DownloadOperator;
import com.kugou.game.sdk.download.DownloadServiceUtil;
import com.kugou.game.sdk.entity.AccountSecurityInfo;
import com.kugou.game.sdk.entity.ForceUpdateInfo;
import com.kugou.game.sdk.interfaces.OnRequestGamecenterRedPointListener;
import com.kugou.game.sdk.interfaces.OnRequestListener;
import com.kugou.game.sdk.interfaces.onAccountSecurityInfoListener;
import com.kugou.game.sdk.persistence.preference.PrefUtil;
import com.kugou.game.sdk.protocol.CheckForceUpdateTask;
import com.kugou.game.sdk.protocol.CheckForceUpdateTask.CheckForceUpdateResponse;
import com.kugou.game.sdk.service.MessageService;
import com.kugou.game.sdk.ui.activity.ForceUpdateActivity;
import com.kugou.game.sdk.ui.widget.FloatView;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.Toast;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述:常用工具类
 * 
 * @author liux
 * @since 2013-12-21 下午03:17:20
 */
public class AppUtil {

    /**
     * 屏幕宽高
     * 
     * @param context
     * @return
     */
    public static int[] getScreenSize(Context context) {
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getApplicationContext().getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;

        return new int[] {
                screenWidth, screenHeight
        };
    }

    /**
     * 根据手机分辨率将dp转为px单位
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取当前日期字符串（格式yyyy-MM-dd）
     */
    public static String getTodayDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String date = format.format(new Date());
        return date;
    }

    /**
     * @param formatStr 格式比如："yyyy-MM-dd"
     * @param timestamp
     * @return
     */
    public static String getDate(String formatStr, long timestamp) {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        String date = format.format(timestamp);
        return date;
    }

    /**
     * 获取屏幕分辨率
     * 
     * @return
     */
    public static Point getDisplayScreenResolution(Context context) {
        int ver = Build.VERSION.SDK_INT;

        DisplayMetrics dm = new DisplayMetrics();
        android.view.Display display = ((WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        display.getMetrics(dm);

        int screen_h = 0, screen_w = 0;
        screen_w = dm.widthPixels;

        if (ver < 13) {
            screen_h = dm.heightPixels;
        } else if (ver == 13) {
            try {
                Method mt = display.getClass().getMethod("getRealHeight");
                screen_h = (Integer) mt.invoke(display);
            } catch (Exception e) {
            }
        } else if (ver > 13) {
            try {
                Method mt = display.getClass().getMethod("getRawHeight");
                screen_h = (Integer) mt.invoke(display);

            } catch (Exception e) {
            }
        }

        return new Point(screen_w, screen_h);
    }

    /**
     * 回收资源
     */
    public static void gc() {
        try {
            Class localClass = Class.forName("android.app.ActivityThread");
            Method localMethod = localClass.getMethod("currentActivityThread", new Class[0]);
            Object localObject1 = localMethod.invoke(localClass,new Object[0]);
            Field localField1 = localClass.getDeclaredField("mActivities");
            localField1.setAccessible(true);
            Map localHashMap = null;
            if (localHashMap == null) {
                localHashMap = (Map) localField1.get(localObject1);
            }
            Iterator localIterator = localHashMap.entrySet().iterator();
            while (localIterator.hasNext()) {
                Map.Entry localEntry = (Map.Entry) localIterator.next();
                Object localObject2 = localEntry.getValue();
                Object localObject3 = null;
                Class[] arrayOfClass = localClass.getDeclaredClasses();
                for (Object localObject5 : arrayOfClass) {
                    if ((((Class) localObject5).getSimpleName().equals("ActivityRecord"))
                            || (((Class) localObject5).getSimpleName()
                                    .equals("ActivityClientRecord"))) {
                        localObject3 = localObject5;
                        break;
                    }
                }
                Field localField4 = ((Class) localObject3).getDeclaredField("paused");
                localField4.setAccessible(true);
                boolean bool1 = ((Boolean) localField4.get(localObject2)).booleanValue();
                Field localField2 = ((Class) localObject3).getDeclaredField("stopped");
                localField2.setAccessible(true);
                boolean bool2 = ((Boolean) localField2.get(localObject2)).booleanValue();
                if ((bool1) || (bool2)) {
                    Field localField3 = ((Class) localObject3).getDeclaredField("activity");
                    localField3.setAccessible(true);
                    Activity localActivity = (Activity) localField3.get(localObject2);
                    localActivity.finish();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final String LOG_SWITCH = "kg00008888";

    /**
     * 打开日志开关
     * 
     * @param tag
     */
    public static boolean turnOnLogSwitch(String tag) {
        if (!TextUtils.isEmpty(tag)) {
            if (tag.equals(LOG_SWITCH)) {
                LogUtil.setDebug(true);
                return true;
            }
        }
        return false;
    }

    /**
     * 获取SDK崩溃异常报告
     * 
     * @param ex
     * @return
     */
    public static String getCrashReport(Throwable ex) {
        StringBuffer sb = new StringBuffer("");
        try {
            if (ex != null) {
                StringWriter writer = new StringWriter();
                PrintWriter printWriter = new PrintWriter(writer);
                ex.printStackTrace(printWriter);
                Throwable cause = ex.getCause();
                while (cause != null) {
                    cause.printStackTrace(printWriter);
                    cause = cause.getCause();
                }
                printWriter.close();
                String result = writer.toString();
                sb.append(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString() + "\nPID=" + android.os.Process.myPid();
    }

    /**
     * 保存异常日志
     * 
     * @param ex
     */
    public static void saveErrorLog(Exception ex) {
        if (ex == null) {
            return;
        }
        String errorlog = "error.log";
        String savePath = FolderManager.LOG_FOLDER;
        String logFilePath = "";
        FileWriter fw = null;
        PrintWriter pw = null;
        try {
            // 判断是否挂载了SD卡
            String storageState = Environment.getExternalStorageState();
            if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                logFilePath = savePath + errorlog;
            }
            // 没有挂载SD卡，无法写文件
            if (logFilePath == "") {
                return;
            }
            File logFile = new File(logFilePath);
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
            fw = new FileWriter(logFile, true);
            pw = new PrintWriter(fw);
            pw.println("------------" + (new Date().toLocaleString()) + "-------------");
            ex.printStackTrace(pw);
            pw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 保存常规日志
     * 
     * @param ex
     */
    public static void saveRegularLog(String log) {
        if (log == null) {
            return;
        }
        String errorlog = "regular.log";
        String savePath = FolderManager.LOG_FOLDER;
        String logFilePath = "";
        FileWriter fw = null;
        PrintWriter pw = null;
        try {
            String storageState = Environment.getExternalStorageState();
            if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                logFilePath = savePath + errorlog;
            }
            if (logFilePath == "") {
                return;
            }
            File logFile = new File(logFilePath);
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
            fw = new FileWriter(logFile, true);
            pw = new PrintWriter(fw);
            pw.println("------------" + (new Date().toLocaleString()) + "-------------");
            pw.println(log);
            pw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 收集调试信息
     */
    public static void gatherDebugInfo(Context context) {
        StringBuilder sb = new StringBuilder();
        String params = SDKControler.getConfigParams();
        String netType = NetWorkUtil.getNetworkType(context);
        boolean netAvailable = NetWorkUtil.isNetworkAvailable(context);
        sb.append(params).append("----").append("\n").append("netType:" + netType).append("\n")
                .append("netAvailable:" + netAvailable).append("\n").append("----").append("\n")
                .append("PhoneModel:" + getPhoneModel()).append("\n")
                .append("SysVersion:" + getSysVersionName()).append("\n")
                .append("Sdk:" + getSdkInt()).append("\n")
                .append("ScreenSize:" + getScreenSizeStr(context)).append("\n")
                .append("hasSDCard:" + hasSDCard()).append("\n")
                .append("phoneMemory:" + getAvailableInternalMemorySize()).append("\n")
                .append("TotalMemorySize:" + getTotalInternalMemorySize()).append("\n")
                .append("----").append("\n")
                .append("SDK_VERSION:" + SDKControler.getSDKVersionName()).append("\n");
        // 打印CP获取的用户信息
        User user = KGPlatform.getCurrentUser();
        if (user != null) {
            sb.append("1、openid(用户唯一标识)：" + user.getOpenId() + "\n")
                    .append("2、username：" + user.getAccountName() + "\n")
                    .append("3、nickname：" + user.getNickName() + "\n")
                    .append("4、token：" + user.getToken() + "\n")
                    .append("5、unixTime：" + user.getUnixTime() + "\n")
                    .append("6、bindPhoneNum：" + user.getBindPhoneNum() + "\n")
                    .append("7、kugouid：" + user.getKugouid() + "\n\n");
        } else {
            sb.append("当前用户信息为空" + "\n");
        }
        // saveRegularLog(sb.toString());
        LogUtil.d("logswitch", sb.toString());
    }

    /**
     * 获取手机型号
     * 
     * @return
     */
    public static String getPhoneModel() {
        String model = Build.MODEL;
        if (!TextUtils.isEmpty(model)) {
            // 防止有非法字符
            String encodeModel = model.replaceAll("[^A-Za-z_0-9 .]", "");
            return encodeModel;
        } else {
            return "";
        }
    }

    /**
     * 获取系统版本，如1.5,2.1
     * 
     * @return　SDK版本号
     */
    public static String getSysVersionName() {
        String version = Build.VERSION.RELEASE;
        if (!TextUtils.isEmpty(version)) {
            String encodeVersion = version.replaceAll("[^A-Za-z_0-9 .]", "");
            return encodeVersion;
        } else {
            return "";
        }
    }

    /**
     * 获取SDK版本号
     * 
     * @return
     */
    public static int getSdkInt() {
        return Build.VERSION.SDK_INT;
    }

    /**
     * 屏幕宽高，字符串形式
     * 
     * @param context
     * @return
     */
    public static String getScreenSizeStr(Context context) {
        int[] screenSize = getScreenSize(context);
        return screenSize[0] + "*" + screenSize[1];
    }

    /**
     * 判断是否存在SDCard
     * 
     * @return
     */
    public static boolean hasSDCard() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) {
            return false;
        }
        return true;
    }

    /**
     * 这个是手机内存的可用空间大小
     * 
     * @return
     */
    public static long getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * 这个是手机内存的总空间大小
     * 
     * @return
     */
    public static long getTotalInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    }

    /**
     * 获取手机唯一码，把imei和mac地址串联起来作为手机唯一标识
     */
    public static String getMachineSN(Context context) {
        String imei = "";
        try {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            imei = tm.getDeviceId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String macAddr = getMACAddr(context);
        return MD5Util.getMd5(imei + macAddr);
    }

    /**
     * MAC地址
     * 
     * @return
     */
    public static String getMACAddr(Context context) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        String macAddr = sp.getString("mac_addr", "");
        if (TextUtils.isEmpty(macAddr)) {
            try {
                WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                macAddr = wifi.getConnectionInfo().getMacAddress();
                if (macAddr == null) {
                    macAddr = "";
                }
            } catch (Exception e) {
                macAddr = "";
            }
            if (!TextUtils.isEmpty(macAddr)) {
                sp.edit().putString("mac_addr", macAddr).commit();
            }
        }
        return macAddr;
    }

    /**
     * 获取版本号
     * 
     * @return
     */
    public static int getVersionCode(Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取版本名称
     * 
     * @return
     */
    public static String getVersionName(Context context) {
        final String packageName = context.getPackageName();
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
            return info.versionName.replaceAll("[^A-Za-z_0-9 .]", "");
        } catch (NameNotFoundException e) {
            return "";
        }
    }

    /**
     * 加多一层封装，用于上传给服务器。 网络类型，1=wifi，2=2g，3=3g，4=4g,5=未知
     * 
     * @param context
     * @return
     */
    public static int getNetworkType(Context context) {
        String netType = NetWorkUtil.getNetworkType(context);
        if (NetWorkUtil.NetworkType.WIFI.equals(netType)) {
            return 1;
        } else if (NetWorkUtil.NetworkType.NET_2G.equals(netType)) {
            return 2;
        } else if (NetWorkUtil.NetworkType.NET_3G.equals(netType)) {
            return 3;
        } else if (NetWorkUtil.NetworkType.NET_4G.equals(netType)) {
            return 4;
        } else {
            return 5;
        }
    }

    /**
     * 把一些相关信息写到sso里去
     * 
     * @param user
     */
    public static void writeDataToSSO(User user) {
        // int gameType = SDKControler.getGameType();
        // Context context = (gameType == ConfigManager.GAMETYPE_NET_GAME ?
        // KYPlatform.getContext()
        // : KYPlatformForSingle.getContext());
        Context context = SDKControler.getContext();

        Bundle bundle = new Bundle();
        try {
            bundle.putLong("userId", Long.valueOf(user.getKugouid()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        bundle.putString("accessToken", user.getKugouToken());

        bundle.putString("userName", user.getAccountName());

        bundle.putLong("appId", SDKControler.getAppId());
        bundle.putString("appKey", SDKControler.getAppKey());
        bundle.putString("code", SDKControler.getCode());
        bundle.putInt("versionCode", AppUtil.getVersionCode(context));
        bundle.putString("machineSN", AppUtil.getMachineSN(context));
        bundle.putString("packageName", context.getPackageName());

        // KugouSDK.saveTicket(bundle);
    }

    /**
     * 组建json
     * 
     * @return
     */
    public static String convertHashMapToJson(HashMap<String, Object> mParams) {

        if (mParams != null && mParams.size() >= 0) {
            JSONObject jsObj = new JSONObject();
            final Set<String> keys = mParams.keySet();
            for (String key : keys) {
                try {
                    jsObj.put(key, mParams.get(key));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return jsObj.toString();
        }
        return "";

    }

    /**
     * 从下载url中截取文件名
     * 
     * @param url
     * @return
     */
    public static String getFileNameFromUrl(String url) {
        if (TextUtils.isEmpty(url) || url.lastIndexOf("/") == -1) {
            return "";
        }
        return url.substring(url.lastIndexOf("/") + 1);
    }

    /**
     * 获取当前进程名称
     * 
     * @param context
     * @return
     */
    public static String getCurrentProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> infos = am.getRunningAppProcesses();
        if (infos != null && infos.size() > 0) {
            for (RunningAppProcessInfo appProcess : infos) {
                if (appProcess.pid == pid) {
                    return appProcess.processName;
                }
            }
        }
        return "";
    }

    /**
     * 获取状态栏高度
     * 
     * @param context
     * @return
     */
    public static int getStateHeight(Context context) {
        int statusHeight = 0;
        if (context instanceof Activity) {
            Rect localRect = new Rect();
            ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
            statusHeight = localRect.top;
        }
        if (!(context instanceof Activity) || 0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject)
                        .toString());
                statusHeight = context.getResources().getDimensionPixelSize(i5);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }

    /**
     * 获取运营商<br>
     * 1、移动，2、联通，3、电信，4、其他
     * 
     * @param context
     * @return
     */
    public static String getMNCNum(Context context) {
        String mnc = "4";
        String state = getMNC(context);
        if (state.equals("46000") || state.equals("46002") || state.equals("46007")) {
            mnc = "1";
        } else if (state.equals("46001")) {
            mnc = "2";
        } else if (state.equals("46003")) {
            mnc = "3";
        }
        return mnc;
    }

    /**
     * 获取运营商<br>
     * 其中46000、46002和46007标识中国移动，46001标识中国联通，46003标识中国电信
     * 
     * @param context
     * @return
     */
    public static String getMNC(Context context) {
        String providersName = "";
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager.getSimState() == TelephonyManager.SIM_STATE_READY) {
            providersName = telephonyManager.getSimOperator();
            providersName = providersName == null ? "" : providersName;
        }
        return providersName;
    }

    /**
     * 检查应用是否已安装（包名一致即可）
     * 
     * @param context
     * @param packageName
     * @return
     */
    public static boolean checkAppExistSimple(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            if (pi != null) {
                return packageName.equals(pi.packageName);
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 打开应用
     * 
     * @param context
     * @param packageName
     */
    public static void openApp(Context context, String packageName) {
        try {
            // 如果在应用里打开本身，则关闭所有SDK界面，回到游戏（如：游戏中心列表中启动自身）
            if (context.getPackageName().equalsIgnoreCase(packageName)) {
                context.sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
                return;
            }

            if (!TextUtils.isEmpty(packageName)) {
                if (checkAppExistSimple(context, packageName)) {
                    PackageManager pm = context.getPackageManager();
                    Intent intent = pm.getLaunchIntentForPackage(packageName);
                    if (intent != null) {
                        List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(
                                intent, 0);
                        if (list != null) {
                            // 如果这个Intent有1个及以上应用可以匹配处理，则选择第一个匹配的处理，防止选择处理类ResolverActivity缺失导致异常崩溃
                            if (list.size() > 0) {
                                ResolveInfo ri = list.iterator().next();
                                if (ri != null) {
                                    ComponentName cn = new ComponentName(
                                            ri.activityInfo.packageName, ri.activityInfo.name);
                                    Intent launchIntent = new Intent();
                                    launchIntent.setComponent(cn);
                                    launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    context.startActivity(launchIntent);
                                }
                            }
                        }
                        return;
                    }
                }
                Toast.makeText(context, "该应用已卸载", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(context, "该应用不能正常启动", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    /**
     * 通过网址打开一个链接
     * 
     * @param url 网址
     */
    public static void openNetUrl(String url, Context context) {
        Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(it);
    }

    /**
     * 打开系统默认浏览器
     * 
     * @param url
     * @param context
     */
    public static void openSystemBrowser(Context context, String url) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            openNetUrl(url, context);
        }
    }

    /**
     * 删除下载文件
     * 
     * @param file
     * @param deleteFile 是否删除下载文件
     */
    public static void deleteDownloadFile(DownloadFile file, boolean deleteFile) {
        Context context = SDKControler.getContext();
        String key = file.getKey();
        DownloadHelper.stopDownload(key);
        DownloadOperator.getInstance().delete(key);

        // 清除缓存里对应的下载信息
        DownloadServiceUtil.removeDownloadFileFromCache(key);
        DownloadServiceUtil.removeFromWaittingQueue(key);

        Intent intent = new Intent(SDKActions.ACTION_DELETE_DOWNLOADFILE);
        intent.putExtra("downloadfile_key", key);
        context.sendBroadcast(intent);
        if (deleteFile) {
            FileUtil.deleteFile(file.getFilePath());
        }
    }

    /**
     * 毫秒转为HH:mm:ss
     * 
     * @param l
     * @return
     */
    public static String formatLongToTimeStr(Long l) {
        int hour = 0;
        int minute = 0;
        int second = 0;

        second = l.intValue() / 1000;

        if (second > 60) {
            minute = second / 60;
            second = second % 60;
        }
        if (minute > 60) {
            hour = minute / 60;
            minute = minute % 60;
        }
        return (addZoro(hour) + ":" + addZoro(minute) + ":" + addZoro(second));
    }

    private static String addZoro(int s) {
        return s < 10 ? "0" + s : s + "";
    }

    /**
     * 获取MD5
     * 
     * @param merchantId
     * @param appId
     * @param appKey
     * @return
     */
    public static String getMd5Str(int merchantId, long appId, String appKey) {
        return MD5Util.getMd5(String.valueOf(merchantId) + String.valueOf(appId) + appKey
                + MD5Util.getEncryptStr());
    }

    /**
     * 获取加密串
     * 
     * @param merchantId
     * @param appId
     * @param appKey
     * @param params
     * @return
     */
    public static String getSign(int merchantId, long appId, String appKey, String username,
            String kgtoken, String imei, int sdkVersionCode) {
        return MD5Util.getMd5(String.valueOf(merchantId) + String.valueOf(appId) + appKey
                + username + kgtoken + imei + sdkVersionCode + MD5Util.getEncryptStr());
    }

    /**
     * 加密
     * 
     * @param source
     */
    public static void encrypt(byte[] source) {
        if (source != null && source.length > 0) {
            int length = source.length;
            byte[] encrypt_key = MD5Util.hexStringToByte(SecurityUtil.getA());
            int keyLen = encrypt_key.length;
            for (int i = 0; i < length; i++) {
                source[i] ^= encrypt_key[i % keyLen];
            }
        }
    }

    /**
     * 解密
     * 
     * @param source
     */
    public static void unEncrypt(byte[] source) {
        if (source != null && source.length > 0) {
            int length = source.length;
            byte[] encrypt_key = MD5Util.hexStringToByte(SecurityUtil.getA());
            int keyLen = encrypt_key.length;
            for (int i = 0; i < length; i++) {
                source[i] ^= encrypt_key[i % keyLen];
            }
        }
    }

    /**
     * DES加密
     * 
     * @param str
     * @return
     */
    public static String desEncrypt(String str) {
        return DESUtil.encrypt(str, new String(MD5Util.hexStringToByte(SecurityUtil.getB())));
    }

    /**
     * DES解密
     * 
     * @param str
     * @return
     */
    public static String desDecrypt(String str) {
        return DESUtil.decrypt(str, new String(MD5Util.hexStringToByte(SecurityUtil.getB())));
    }

    /**
     * 生成单机游戏用户名（username）
     */
    public static String getUIDForSingle(Context context) {
        String imei = "";
        try {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            imei = tm.getDeviceId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String macAddr = AppUtil.getMACAddr(context);
        String fingerPrint = Build.FINGERPRINT;
        if (TextUtils.isEmpty(fingerPrint)) {
            fingerPrint = "";
        }
        String timeStamp = System.currentTimeMillis() / 1000l + "";
        return MD5Util.getMd5("ANDROID" + imei + macAddr + fingerPrint + timeStamp);
    }

    /**
     * 使用论坛的rsa公钥进行加密，只用于论坛的数据加密
     * 
     * @param str
     * @return
     */
    public static String getRASEncryptForForum(String str) {
        // 论坛的rsa公钥
        String publicKey = new String(MD5Util.hexStringToByte(SecurityUtil.getE()));
        return RSAUtil.getRASEncrypt(str, publicKey);
    }

    /**
     * 为论坛数据进行md5加密，用于校验
     * 
     * @param userName
     * @param password
     * @return
     */
    public static String getMd5StrForForum(String userName, String password) {
        // return MD5Util.getMd5(userName + password + MD5Util.getEncryptStr());
        // 论坛的md5Key（md5校验串）
        String md5Key = new String(MD5Util.hexStringToByte(SecurityUtil.getF()));
        return MD5Util.getMd5(userName + password + md5Key).toLowerCase();
    }

    /**
     * 登录成功后的一些相关操作
     * 
     * @param eventCode
     */
    public static void handleActionsAfterLoginSuccess(final int eventCode) {
        // 通知悬浮窗
        FloatView.createAndSendUpdateIntent(SDKControler.getContext(),
                SDKActions.ACTION_UPDATE_TOOLBAR_AFTER_LOGIN_SUCCESS);

        ThreadTaskManager.excuteTask(new Runnable() {
            @Override
            public void run() {
                switch (eventCode) {
                    case IEventCode.ENTER_GAME_SUCCESS:
                        if (SDKControler.isSupportForceUpdate()) {
                            checkForceUpdate(SDKControler.getContext().getApplicationContext());
                        }
                        UserManager.getInstance().requestUserCenterBanner(new OnRequestListener() {

                            @Override
                            public void onSuccess() {
                            }

                            @Override
                            public void onFailed(String errorMsg) {
                            }
                        });
                    case IEventCode.REGISTER_SUCCESS:
                    case IEventCode.ACCOUNT_CHANGED_SUCCESS:
                        // 登录成功请求用户安全信息，主要用于游币充值成功是否弹出设置支付密码的判断
                        UserManager.getInstance().requestAccountSecurityInfo(
                                new onAccountSecurityInfoListener() {

                                    @Override
                                    public void onSuccess(AccountSecurityInfo info) {
                                    }

                                    @Override
                                    public void onFaile(String errorMsg) {
                                    }
                                });
                        // 请求兑换比例
                        PayManager.requestExchangeRatio();
                        // 请求代金券信息
                        PayManager.requestCouponInfo(null);
                        // 请求悬浮窗游戏中心红点数据
                        requestGamecenterRedpointData();
                        // 请求礼包信息
                        UserManager.getInstance().requestGiftBagState(new OnRequestListener() {
                            @Override
                            public void onSuccess() {
                                FloatView.createAndSendUpdateIntent(SDKControler.getContext(),
                                        SDKActions.ACTION_STATE_HAS_GIFTBAG);
                            }

                            @Override
                            public void onFailed(String errorMsg) {

                            }
                        });
                        VipManager.getInstance().requestVipInfos(false, null);
                        break;
                }
            }
        });
    }

    private static void checkForceUpdate(final Context context) {
        CheckForceUpdateTask task = new CheckForceUpdateTask();
        CheckForceUpdateResponse response = task.request(SDKControler.getMerchantId(),
                SDKControler.getAppId(), SDKControler.getChannelId(), SDKControler.getGameId(),
                context.getPackageName(), SDKControler.getAppKey());
        if (response == null || !response.isOk()) {
            return;
        }
        ForceUpdateInfo forceUpdateInfo = response.getForceUpdateInfo();
        if (forceUpdateInfo.getVersionCode() > getVersionCode(context)
                && forceUpdateInfo.isUpdate()) {
            final ForceUpdateInfo info = forceUpdateInfo;
            PlatformEventDispatcher.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(context, ForceUpdateActivity.class);
                    intent.putExtra("checkUpdateInfo", info);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            });
        }
    }

    private static void requestGamecenterRedpointData() {
        new Thread() {
            @Override
            public void run() {
                final Context context = SDKControler.getContext();
                User user = UserManager.getInstance().getCurrentUserInternal();
                String kugouid = "0";
                if (user != null) {
                    kugouid = user.getKugouid();
                }

                String imei = AppUtil.getMachineSN(context);
                int nettype = AppUtil.getNetworkType(context);
                String mid = AppUtil.getKugouMID(context);
                String uuid = AppUtil.getKugouUUID(context);
                UserManager.getInstance().requestGamecenterRedpointTip(kugouid, imei, nettype, mid,
                        uuid, new OnRequestGamecenterRedPointListener() {
                            @Override
                            public void onSuccess(String response) {
                                if (!TextUtils.isEmpty(response)) {
                                    // 服务器返回的游戏中心数据与本地之前数据不同,通知显示红点提示
                                    if (!response.trim().equals(
                                            PrefUtil.getGamecenterRedpointData(context))) {
                                        // 把数据临时存储起来
                                        PrefUtil.setGamecenterRedpointDataTemp(context,
                                                response.trim());

                                        UserManager.getInstance().getCurrentUserInternal()
                                                .setGameCenterNeedRedPointRemind(true);
                                        PlatformEventDispatcher.runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                // 通知悬浮窗
                                                FloatView
                                                        .createAndSendUpdateIntent(
                                                                context,
                                                                SDKActions.ACTION_UPDATE_TOOLBAR_AFTER_LOGIN_SUCCESS);
                                            }
                                        });
                                    }
                                }
                            }
                        });
            };
        }.start();

    }

    public static String getSignature(Context context, String packageName) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(packageName,
                    PackageManager.GET_SIGNATURES);
            Signature[] asignature = pi.signatures;
            int j = asignature.length;
            for (int i = 0; i < j; i++) {
                Signature signature = asignature[i];
                String s = MD5Util.getMd5(signature.toByteArray());
                if (!TextUtils.isEmpty(s)) {
                    return s;
                }
            }
            return "";
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 把IMEI用一大整数代替
     * 
     * @param imei
     * @return
     */
    public static String imeiToBigInteger(String imei) {
        BigInteger result = new BigInteger("0");
        try {
            BigInteger n = new BigInteger("16");
            String md5 = MD5Util.getMd5(imei).toLowerCase();
            int size = md5.length();
            for (int i = 0; i < size; i++) {
                BigInteger a = new BigInteger("" + md5.charAt(i), 16);
                BigInteger b = n.pow(size - 1 - i);
                result = result.add(a.multiply(b));
            }
            return result.toString();
        } catch (Exception e) {
        }
        return result.toString();
    }

    /**
     * 获取手机串号(IMEI), 为空时返回MAC地址
     * 
     * @param context
     * @return
     */
    public static String getIMEIByKG(Context context) {
        String imei = "";
        try {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            imei = tm.getDeviceId();
        } catch (Exception e) {
        }
        // 平板imei为null
        if (TextUtils.isEmpty(imei)) {
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            if (info != null) {
                imei = info.getMacAddress();
            }
            if (imei == null) {
                imei = "";
            }
        }
        return imei;
    }

    /**
     * 获取酷狗平台统计字段：用户标识（mid）
     * 
     * @param context
     * @return mid
     */
    public static String getKugouMID(Context context) {
        return imeiToBigInteger(getIMEIByKG(context));
    }

    /**
     * 获取酷狗平台统计字段：通用唯一标识符（uuid）
     * 
     * @param context
     * @return uuid
     */
    public static String getKugouUUID(Context context) {
        String uuid = PrefUtil.getKugouUUID(context);
        if (TextUtils.isEmpty(uuid)) {
            uuid = UUID.randomUUID().toString().replace("-", "");
            PrefUtil.setKugouUUID(context, uuid);
        }
        return uuid;
    }

    /**
     * 将数字大小转换成“MB"、“KB”、"GB"格式
     * 
     * @param size
     * @return
     */
    public static String getSize(long size) {
        if (size < 0)
            return null;

        String result = null;
        if (size > 1024 * 1024 * 1024) {
            float f = (float) size / (1024 * 1024 * 1024);
            String s = String.valueOf(f);
            if (s.length() - s.indexOf(".") > 2)
                result = s.substring(0, s.indexOf(".") + 3);
            else
                result = s;
            return result + "GB";
        } else if (size > 1024 * 1024) {
            float f = (float) size / (1024 * 1024);
            String s = String.valueOf(f);
            if (s.length() - s.indexOf(".") > 2)
                result = s.substring(0, s.indexOf(".") + 3);
            else
                result = s;
            return result + "MB";
        } else if (size > 1024) {
            float f = (float) size / 1024;
            String s = String.valueOf(f);
            if (s.length() - s.indexOf(".") > 2)
                result = s.substring(0, s.indexOf(".") + 3);
            else
                result = s;
            return result + "KB";
        } else if (size < 1024) {
            return String.valueOf(size) + "B";
        } else
            return null;
    }

    /**
     * 安装应用
     * 
     * @param filehash
     * @return int 默认0；1安装文件不存在；2安装文件错误
     */
    public static int installApp(Context context, String filehash) {
        DownloadFile file = DownloadOperator.getInstance().query(filehash);
        if (file != null) {
            String filePath = file.getFilePath();
            if (!FileUtil.isFileExist(filePath)) {
                // 删除该条应用的本地记录和缓存信息
                DownloadOperator.getInstance().delete(filehash);
                DownloadServiceUtil.removeDownloadFileFromCache(filehash);
                return 1;
            } else {
                if (filePath.endsWith(FileDownloader.TEMP_FILE_EXT_NAME)) {
                    String newFilePath = filePath.replace(FileDownloader.TEMP_FILE_EXT_NAME, "");
                    FileUtil.rename(filePath, newFilePath);
                    filePath = newFilePath;
                }

                if (context.getPackageManager().getPackageArchiveInfo(filePath, 0) == null) {
                    return 2;
                } else {
                    InstallHelper.getInstance().install(filePath);
                }
            }
        }
        return 0;
    }

    /**
     * 设置淡入动画
     * 
     * @param view 控件
     * @param startOffset　廷迟毫秒数
     */
    public static void setFadeIn(Context context, View view, long startOffset) {
        Animation fade_in = AnimationUtils.loadAnimation(context, Rx.anim.kg_anim_fade_in);
        fade_in.setDuration(600);
        fade_in.setStartOffset(startOffset);
        fade_in.setInterpolator(new DecelerateInterpolator());
        view.startAnimation(fade_in);
    }

    /**
     * 获取应用名称
     * 
     * @return
     */
    public static String getAppName(Context context) {

        PackageManager packageManager = null;
        ApplicationInfo applicationInfo = null;
        try {
            packageManager = context.getApplicationContext().getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName = (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

    /**
     * 获取字符串的长度，中文占2个字符,英文数字占1个字符
     * 
     * @param value 指定的字符串
     * @return 字符串的长度
     */
    public static double length(String value) {
        double valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        // 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1
        for (int i = 0; i < value.length(); i++) {
            // 获取一个字符
            String temp = value.substring(i, i + 1);
            // 判断是否为中文字符
            if (temp.matches(chinese)) {
                // 中文字符长度为2
                valueLength += 2;
            } else {
                // 其他字符长度为1
                valueLength += 1;
            }
        }
        // 进位取整
        return Math.ceil(valueLength);
    }

    /**
     * 是否都是数字
     * 
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 是否含有特殊字符
     * 
     * @param str
     * @return
     */
    public static boolean isSpatialChart(String str) {
        // String str = "/";
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？ ]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
        // return str.matches("[\\x20-\\x7E]*");
    }

    /**
     * 是否含有中文
     * 
     * @param str
     * @return
     */
    public static boolean isHaveChinese(String str) {
        for (int i = 0; i < str.length(); i++) {
            int chr1 = str.charAt(i);
            if (chr1 >= 19968 && chr1 <= 171941) {
                return true;
            }
        }
        return false;
    }

    /**
     * 返回带星号的email
     * 
     * @param email
     * @return
     */
    public static String getEmailWithStar(String email) {
        String emailStar = email;
        if (!TextUtils.isEmpty(email) && email.length() >= 7) {
            emailStar = email.substring(0, 1);
            int start = email.indexOf("@");
            for (int i = 0; i < start - 2; i++) {
                emailStar += "*";
            }

            emailStar += email.substring(start - 1, start);
            emailStar += email.substring(start);
        }

        return emailStar;
    }

    /**
     * 返回带星号的手机号码
     * 
     * @param phone
     * @return
     */
    public static String getPhoneWithStar(String phone) {
        String phoneStar = phone;

        if (!TextUtils.isEmpty(phone) && phone.length() == 11) {
            phoneStar = phone.substring(0, 2) + "*****" + phone.substring(7);
        }

        return phoneStar;
    }

    /**
     * 判断邮箱格式正确
     * 
     * @return boolean
     */
    public static boolean isEmailCorrect(String email) {
        if (TextUtils.isEmpty(email)) {
            return false;
        }

        String regex = "[a-zA-Z0-9_-]+@\\w+\\.[a-z]+(\\.[a-z]+)?";
        Pattern pt = Pattern.compile(regex);
        Matcher mc = pt.matcher(email);
        return mc.matches();
    }

    /**
     * 检查后台服务是否运行
     * 
     * @param context
     * @param serviceClass
     * @return
     */
    public static String isServiceRunning(Context context, Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return service.service.getPackageName();
            }
        }
        return null;
    }

    /**
     * 开启推送服务
     * 
     * @param context
     */
    public static void startPushService(Context context, BaseSDKConfig sdkConfig,
            int sdkversioncode, String sdkversionname) {
        try {
            Intent intent = new Intent();
            intent.setAction(SDKActions.ACTION_START_MESSAGE_SERVICE);
            intent.putExtra(MessageService.INTENT_PACKAGENAME, context.getPackageName());
            intent.putExtra(MessageService.INTENT_MESSAGE_CONFIG,
                    sdkConfig != null && sdkConfig.isPushMessage() ? 1 : 0);
            intent.putExtra(MessageService.INTENT_MESSAGE_TYPE, MessageService.MESSAGE_TYPE);
            String sdkConfigData = convertConfig(sdkConfig, sdkversioncode, sdkversionname);
            intent.putExtra(MessageService.INTENT_MESSAGE_SDK_DATA, sdkConfigData);
            String packegename = isServiceRunning(context, MessageService.class);
            if (!TextUtils.isEmpty(packegename)) {
                intent.setPackage(packegename);
            } else {
                intent.setPackage(context.getPackageName());
            }
            context.startService(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String convertConfig(BaseSDKConfig sdkConfig, int sdkversioncode,
            String sdkversionname) {
        try {
            if (sdkConfig != null) {
                JSONObject obj = new JSONObject();
                obj.put("appid", sdkConfig.getAppId());
                obj.put("appkey", sdkConfig.getAppKey());
                obj.put("gameid", sdkConfig.getGameId());
                obj.put("merchantid", sdkConfig.getMerchantId());
                obj.put("gametype", sdkConfig.getGameType());
                obj.put("sdkversioncode", sdkversioncode);
                obj.put("sdkversionname", sdkversionname);
                return obj.toString();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 检测充值卡号格式是否正确
     * 
     * @param cardNumber
     * @return
     */
    public static boolean isCardNumberCorrect(String cardNumber) {
        if (!TextUtils.isEmpty(cardNumber)) {
            Pattern pattern = Pattern.compile("^\\d{8,}$");
            if (pattern != null) {
                Matcher matcher = pattern.matcher(cardNumber);
                return matcher.find();
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 检测充值卡格式是否正确
     * 
     * @param cardNumber
     * @return
     */
    public static boolean isCardPasswordCorrect(String cardNumber) {

        if (!TextUtils.isEmpty(cardNumber)) {
            Pattern pattern = Pattern.compile("^\\d{8,}$");
            if (pattern != null) {
                Matcher matcher = pattern.matcher(cardNumber);
                return matcher.find();
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 判断充值输入金额是否正确
     * 
     * @param value
     * @return
     */
    public static boolean checkRechargeValueInput(String value) {

        if (!TextUtils.isEmpty(value)) {
            String reg = "[1-9][0-9]*";
            return value.matches(reg);
        } else {
            return false;
        }
    }

    /**
     * 获取当前在最上方的Activity
     * 
     * @param context
     * @return
     */
    public static String getCurrentActivity(Context context) {
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);

        return rti.get(0).topActivity.getClassName();
    }

    /**
     * 获取密钥
     *
     * @return
     */
    public static String getEncryptStr() {
        byte[] data = MD5Util.hexStringToByte(SecurityUtil.getC());
        AppUtil.unEncrypt(data);
        String realStr = new String(data);
        return realStr;
    }
}
